package cn.edu.hznu.notebook.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.hznu.notebook.dao.NoteDao;
import cn.edu.hznu.notebook.dao.NotebookDao;
import cn.edu.hznu.notebook.entity.Note;
import cn.edu.hznu.notebook.entity.Notebook;

@Service("NoteService")
@Transactional(rollbackFor = {Exception.class})
public class NoteServiceImpl implements NoteService{

	@Autowired
	NoteDao noteDao;
	@Autowired
	NotebookDao notebookDao;
	
	
	@Override
	public void addNewNote(Note note) throws Exception {
		Optional.ofNullable(note.getNotebook())
				.orElseThrow(() ->
						new Exception("The note's notebook should not be null."));
		this.noteDao.save(note);
		Notebook notebook = this.notebookDao
				.findById(note.getNotebook().getId());
		notebook.setNoteSum(notebook.getNoteSum() + 1);
		this.notebookDao.update(notebook);
	}

	@Override
	public Note getNoteById(Integer id) {
		return this.noteDao.findById(id);
	}

	@Override
	public List<Note> getNotesByNotebook(Notebook notebook) {
		List<Note> notes = this.noteDao.findByNotebook(notebook);
		notes.forEach(note -> note.setNotebook(notebook));
		return notes;
	}

	@Override
	public void updateNoteInfo(Note note) throws Exception {
		Optional.ofNullable(note.getNotebook())
				.orElseThrow(() ->
					new Exception("The note's notebook should not be null."));
		this.noteDao.update(note);
	}

	@Override
	public void deleteNote(Note note) throws Exception {
		Optional.ofNullable(note.getNotebook())
				.orElseThrow(() -> 
					new Exception("The note's notebook should not be null."));
		this.noteDao.delete(note);
		Notebook notebook = this.notebookDao
				.findById(note.getNotebook().getId());
		notebook.setNoteSum(notebook.getNoteSum() - 1);
		this.notebookDao.update(notebook);
	}

	@Override
	public void deleteNote(Integer id) throws Exception {
		Note note = this.noteDao.findById(id);
		this.noteDao.delete(note);
		Notebook notebook = this.notebookDao
				.findById(note.getNotebook().getId());
		notebook.setNoteSum(notebook.getNoteSum() - 1);
		this.notebookDao.update(notebook);
	}

}
